package dom;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class TestB {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(TestB.class.getClassLoader().getResourceAsStream("b.xml"));

       NodeList nodeList = doc.getElementsByTagName("stu");
       for(int i = 0; i < nodeList.getLength(); i++){
           Element element = (Element) nodeList.item(i);
           String name = getElementText(element,"name");
           String age = getElementText(element,"age");
           String gender = getElementText(element,"gender");
           System.out.println(name+"\t"+age+"\t"+gender);
       }
    }

    public static String getElementText(Element parent,String name){
        Element elementChild = parent.getElementsByTagName(name).getLength()>0
                ?(Element) parent.getElementsByTagName(name).item(0)
                :null;
        return elementChild == null?null:elementChild.getTextContent();
    }
}
